<template>
  <div class="cust_route_node_edit">
    <!--顶部保存和删除按钮-->
    <!--
    <div class="btn_box">
      <el-button type="primary" class="primary_btn" @click="saveObj">{{$t('public.save')}}</el-button>
      <el-button v-show="nodeObj._id && showDeleteBtn" type="primary" class="primary_btn delete_btn" @click="deleteCusrRouteNode">{{$t('public.delete')}}</el-button>
    </div>
    -->
    <br/>
    <div class="remark">{{$t('configLazyLoad.process.processLabel18')}}<a href="http://help.7moor.com/%E4%BA%91%E5%AE%A2%E6%9C%8D/%E5%9C%A8%E7%BA%BF%E5%92%A8%E8%AF%A2/%E6%97%A5%E7%A8%8B%E7%AE%A1%E7%90%86/%E8%8A%82%E7%82%B9%E7%AE%A1%E7%90%86"  target="_Blank">{{$t('configLazyLoad.process.processLabel19')}}</a></div>
    <!-- 节点名称 -->
    <el-form :model="nodeObj" label-width="90px" ref="nodeObj" :rules="rules">
      <el-form-item :label="$t('configLazyLoad.process.nodeName')" prop="name" class="form_li node_name">
        <el-input :maxlength="30" v-model.trim="nodeObj.name" class="input_box"></el-input>
      </el-form-item>
    </el-form>
    <br/>
    <!-- 路由table -->
    <el-table :data="nodeObj.routeList">
      <el-table-column prop="name" :label="$t('configLazyLoad.process.processLabel20')" >
        <template scope="scope">
          <span>{{ scope.row.name }}</span>
          <question-tooltip
                  v-if="scope.row._id && scope.row._id === 'system'"
                  :tipContent="$t('configLazyLoad.process.processLabel21')"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('configLazyLoad.process.processLabel22')">
        <template scope="scope"><span>{{trigger(scope.row.processType)}}</span></template>
      </el-table-column>
      <el-table-column prop="priority" :label="$t('configLazyLoad.process.processLabel23')">
        <template scope="scope">{{ scope.row.priority }}</template>
      </el-table-column>
      <el-table-column :label="$t('public.operate')">
        <template scope="scope">
          <el-button type="text" @click="editRoute(scope.row, scope.$index)" size="small">{{$t('public.edit')}}</el-button>
          <el-button v-if="scope.row._id !== 'system'" class="delete_text" type="text" @click="removeRoute(scope.row, scope.$index)" size="small">{{$t('public.delete')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加路由按钮 -->
    <div class="add_route_btn_box">
      <span @click="addRoute" class="add_route_btn"><i class="iconfont icon-zhankai"></i>{{$t('configLazyLoad.process.processLabel24')}}</span>
    </div>
    <!-- 添加||修改路由 -->
    <!-- 此处使用v-if的原因：添加节点的时候先添加路由，然后触发转向至为空，虽然重置表单，但是触发转向没有被重置，
    所以会出现修改系统默认节点的时候，一级节点是系统节点，二级节点为空的情况出现  qyg -->
    <el-form v-if="showRouteEdit" class="route_form" :model="routeForm" label-width="140px" ref="routeForm" :rules="routeRules">
      <!-- 分割线 -->
      <div class="divide"></div>
      <div class="route_todo_title">
        <span v-if="routeTodo === 'add'">{{$t('configLazyLoad.process.processLabel24')}}</span>
        <span v-if="routeTodo === 'update'">{{$t('configLazyLoad.process.processLabel25')}}</span>
      </div>
      <div class="remark">
        {{$t('channelsettings.schedule7')}}<br/>
        {{$t('configLazyLoad.process.processLabel26')}}<br/>
        {{$t('configLazyLoad.process.processLabel27')}}<br/>
        {{$t('configLazyLoad.process.processLabel28')}}
      </div>
      <el-form-item :label="$t('configLazyLoad.process.processLabel136') + '：'" class="form_li route_form_li" prop="priority">
        <el-input :maxlength="3" v-model.trim="routeForm.priority" :disabled="routeForm._id && routeForm._id === 'system' ? true : false" value="number" class="input_box"></el-input>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.process.processLabel20') + '：'" class="form_li route_form_li" prop="name">
        <el-input :maxlength="30" v-model.trim="routeForm.name" :disabled="routeForm._id && routeForm._id === 'system' ? true : false" :placeholder="$t('configLazyLoad.process.processLabel47')" class="input_box"></el-input>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.process.processLabel29')" v-if="routeForm._id && routeForm._id === 'system' ? false : true" class="form_li route_form_li" style="width: 100%">
        <div v-for="(itemCon, index) in routeForm.condition" :key="index">
          <el-select class="condition_select" v-model="itemCon.factor" :placeholder="$t('public.pleasePick')" @change="factorChange(index)">
            <el-option
                    v-for="(item, index) in options"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled">
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px" v-if="item.disabled">（{{$t('public.already')}}）</span>
            </el-option>
          </el-select>
          <el-select class="condition_select" v-model="itemCon.contain" :placeholder="$t('public.pleasePick')">
            <el-option v-show="itemCon.factor !== 'area' && itemCon.factor !== 'toCustomer'" :label="$t('configLazyLoad.process.processLabel30')" value="all"></el-option>
            <el-option v-show="itemCon.factor === 'toCustomer'" label="不包含任意一个" value="notIncludeAny"></el-option>
            <el-option :label="$t('configLazyLoad.process.processLabel31')" value="some"></el-option>
          </el-select>
          <!-- 别的条件的input框 -->
          <el-input v-if="itemCon.factor !== 'area' && itemCon.factor !== 'toCustomer'" class="route_content_input" :placeholder="$t('configLazyLoad.process.processLabel32')" v-model.trim="itemCon.content"></el-input>
          <!-- 省份选择select -->
          <el-select v-if="itemCon.factor === 'area'" filterable size="mini" clearable multiple class="province_select" v-model="itemCon.content" collapse-tags :placeholder="$t('public.pleasePick')">
            <el-option
                    v-for="(item, index) in provinces"
                    :label="item.label"
                    :key="index"
                    :value="item.value">
            </el-option>
          </el-select>
          <!-- 客户状态select -->
          <el-select
            class="province_select"
            v-if="itemCon.factor === 'toCustomer'"
            v-model="itemCon.content"
            multiple
            collapse-tags
            placeholder="请选择">
            <el-option
              v-for="(item, index) in custormStatusArr"
              :key="index"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <span @click="removeCondition(index)" v-if="index !== 0" class="el-icon-minus domain_btn"></span>
        </div>
        <div>
          <span @click="addCondition" class="add_condition_btn"><i class="iconfont icon-zhankai"></i>{{$t('configLazyLoad.process.processLabel33')}}</span>
        </div>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.process.processLabel34')" class="form_li route_form_li" prop="processTo">
        <nodeSelect
                @oneChange="onChange"
                onePath="processType"
                :nodeType="routeForm.processType"
                @twoChange="onChange"
                twoPath="processTo"
                :contentId="routeForm._id"
                :nodeLi="routeForm.processTo"
        ></nodeSelect>
      </el-form-item>
    </el-form>
    <!-- 保存路由按钮 -->
    <div class="btn_box">
      <el-button type="primary" class="primary_btn" @click="saveRouteObj">{{$t('public.save')}}</el-button>
    </div>
  </div>
</template>
<script>
  import * as types from '@modules/config/channelConfig/webchatSchdule/mutation-types.js'
  import { deepClone } from '@utils/m7Utils.js'
  import questionTooltip from '@/components/ui-modules/questionToolTip/QuestionToolTip.vue'
  import nodeSelect from '../../../base/webchatNodeSelect.vue'
  export default {
    name: 'custRouteNodeEdit',
    data () {
      return {
        nodeObj: {
          _id: '', // id
          account: '', // 账户id
          type: 'custRoute', // 节点类型
          name: '', // 名称
          createTime: '', // 创建时间
          createUser: '', // 创建人
          updateTime: '', // 修改时间
          updateUser: '', // 修改人
          routeList: [{
            _id: 'system',
            name: this.$t('configLazyLoad.process.processLabel35'),
            processType: 'system',
            processTo: 'finish',
            priority: 99999
          }]
        },
        showRouteEdit: false,
        custormStatusArr: [],
        provinces: [],
        options: [{
          value: 'area',
          label: this.$t('configLazyLoad.process.processLabel36'),
          disabled: false
        }, {
          value: 'keyWord',
          label: this.$t('configLazyLoad.process.processLabel37'),
          disabled: false
        }, {
          value: 'url',
          label: this.$t('configLazyLoad.process.processLabel38'),
          disabled: false
        }, {
          value: 'weChatMini',
          label: this.$t('configLazyLoad.process.processLabel39'),
          disabled: false
        }, {
          value: 'toCustomer',
          label: '客户状态',
          disabled: false
        }],
        routeTodo: 'add',
        routeTodoIndex: -1,
        routeForm: {
          _id: '',
          name: '',
          processType: 'system',
          processTo: 'finish',
          condition: [{
            factor: '',
            contain: 'all',
            content: ''
          }],
          priority: 1
        },
        rules: {
          name: [{required: true, message: this.$t('configLazyLoad.process.processLabel7'), trigger: 'blur'}]
        },
        routeRules: {
          name: [{required: true, message: this.$t('configLazyLoad.process.processLabel40'), trigger: 'blur'}],
          priority: [{required: true, message: this.$t('configLazyLoad.process.processLabel41')}]
        }
      }
    },
    props: {
      showDeleteBtn: {
        type: Boolean,
        default: true
      },
      dataId: {
        type: String,
        default: ''
      },
      random: Number,
      todoType: String
    },
    watch: {
      random (cur, old) {
        this.resetForm()
        this.initData()
      }
    },
    methods: {
//      初始化
      initData () {
        this.showRouteEdit = false
        if (this.dataId) {
          let data = {
            _id: this.dataId
          }
          this.$store.dispatch('getNodeById', data).then((res) => {
            if (res.success) {
              this.$nextTick(() => {
                this.nodeObj = deepClone(res.data)
                this.welMsgUl = deepClone(res.data.welcomeMessages)
                this.welMsg = deepClone(res.data.welcomeMessage)
//                this.initEditor()
                if (this.nodeType === 'single') {
                  this.welcomeMsgEditShow = true
                } else {
                  this.welcomeMsgEditShow = false
                }
              })
            } else {
              this.welMsgUl = []
              this.welMsg = ''
            }
          })
        } else {
          this.nodeObj = {
            _id: '', // id
            account: '', // 账户id
            type: 'custRoute', // 节点类型
            name: '', // 名称
            createTime: '', // 创建时间
            createUser: '', // 创建人
            updateTime: '', // 修改时间
            updateUser: '', // 修改人
            routeList: [{
              _id: 'system',
              name: this.$t('configLazyLoad.process.processLabel35'),
              processType: 'system',
              processTo: 'finish',
              condition: [{
                factor: '',
                contain: 'all',
                content: ''
              }],
              priority: 99999
            }]
          }
          this.welcomeMsgEditShow = true
          this.welMsgUl = []
          this.welMsg = ''
        }
        //          加载省份
        this.$store.dispatch('getCache', { type: 'options', id: 'd7b9c68a-b50f-21d1-d5fd-41ea93f5f49c' }).then((provinceCache) => {
          let provinces = [...provinceCache.options.map(province => ({ label: province.name, value: `${province.key}`, options: province.options }))]
          this.provinces = provinces || []
        })
        // 加载客户状态
        this.$store.dispatch('getCustomerTemplate', {account: this.$store.state.session.user.account}).then(res => {
          if (res.success && res.data && res.data.length > 0) {
            let toCustomer = res.data[0].status
            let customerConfig = res.data[0].statusConfig
            let custormerArr = []
            for (let i in toCustomer) {
              if (customerConfig[i].status !== 'disabled') {
                custormerArr.push({value: i, label: toCustomer[i]})
              }
            }
            this.custormStatusArr = custormerArr
          }
        })
      },
//      重置form表单
      resetForm () {
        this.$refs.nodeObj.resetFields()
//        this.$refs.routeForm.resetFields()
      },
//      删除路由
      removeRoute (data, index) {
        this.$confirm(this.$t('configLazyLoad.process.processLabel42'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.nodeObj.routeList.splice(index, 1)
          this.showRouteEdit = false
        })
      },
//      路由表格的触发转向
      trigger (data) {
        if (data === 'time') {
          return this.$t('configLazyLoad.process.node8')
        } else if (data === 'queue') {
          return this.$t('configLazyLoad.process.node4')
        } else if (data === 'robot') {
          return this.$t('configLazyLoad.process.node9')
        } else if (data === 'system') {
          return this.$t('configLazyLoad.process.node')
        }
      },

//      保存客户路由节点
      saveObj () {
        let that = this
        this.$refs['nodeObj'].validate((valid) => {
          if (valid) {
            if (that.todoType === 'add') {
              that.$store.dispatch('addNode', that.nodeObj).then((res) => {
                if (res.success) {
                  that.$store.commit(types.ADD_WEBCHAT_SCHDULE_LIST_NODE, {node: 'custRouteNode', data: that.nodeObj})
                  that.$message.success(this.$t('config.channel.saveSuccess'))
                  that.$emit('back')
                }
              })
            } else {
              that.$store.dispatch('updateNode', that.nodeObj).then((res) => {
                if (res.success) {
                  that.$store.commit(types.UPDATE_WEBCHAT_SCHDULE_LIST_NODE, {node: 'custRouteNode', data: that.nodeObj})
                  that.$message.success(this.$t('config.channel.saveSuccess'))
                  that.$emit('back')
                }
              })
            }
          }
        })
      },
//      编辑路由
      editRoute (data, index) {
//        this.$refs.routeForm.resetFields()
        this.routeForm = deepClone(data)
        this.routeTodo = 'update'
        this.routeTodoIndex = index
        this.showRouteEdit = true
        this.optionsChange()
      },
//      添加路由
      addRoute () {
        this.routeTodo = 'add'
        this.routeForm = {
          _id: '',
          name: '',
          processType: 'system',
          processTo: 'finish',
          condition: [{
            factor: '',
            contain: 'all',
            content: ''
          }],
          priority: 1
        }
        this.showRouteEdit = true
        this.options.forEach((item) => {
          item.disabled = false
        })
      },
//      触发转向变更
      onChange (data) {
        this.routeForm[data.path] = data.value
      },
//      保存路由信息
      saveRouteObj () {
        let that = this
        if (that.showRouteEdit) {
          that.$refs.routeForm.validate((valid) => {
            if (valid) {
              let conditionFlag = true
              if (!that.routeForm._id) {
                that.routeForm.condition.forEach((item) => {
                  if (!item.content || !item.content.length) {
                    conditionFlag = false
                  }
                  if (item.factor === 'area') {
                    let arr = []
                    for (let i = 0; i < that.provinces.length; i++) {
                      for (let p = 0; p < item.content.length; p++) {
                        if (that.provinces[i].value === item.content[p]) {
                          arr.push(that.provinces[i].label)
                        }
                      }
                    }
                    that.$set(item, 'name', arr)
                  }
                })
              }
              var regu = /^[0-9]*[1-9][0-9]*$/
              if (!regu.test(that.routeForm.priority)) {
                this.$message.error(this.$t('configLazyLoad.process.processLabel43'))
                return false
              }
              if (!conditionFlag) {
                that.$message.error(this.$t('configLazyLoad.process.processLabel44'))
                return
              }
              if (!that.routeForm.processType) {
                that.$message.error(this.$t('configLazyLoad.process.processLabel45'))
                return
              }
              if (that.routeTodo === 'add') {
                that.nodeObj.routeList.push(deepClone(that.routeForm))
              } else {
                that.$set(that.nodeObj.routeList, [that.routeTodoIndex], deepClone(that.routeForm))
              }
              that.showRouteEdit = false
              that.saveObj()
            }
          })
        } else {
          that.saveObj()
        }
      },
//      触发条件变更
      factorChange (index) {
//        地域的省份值是id，切换的时候需要清除掉
        this.routeForm.condition[index].content = ''
        if (this.routeForm.condition[index].factor === 'area') {
          this.routeForm.condition[index].contain = 'some'
        } else if (this.routeForm.condition[index].factor === 'toCustomer') {
          this.routeForm.condition[index].contain = 'notIncludeAny'
        }
        this.optionsChange()
      },
//      触发条件更改的时候的函数
      optionsChange () {
        let that = this
        that.options.forEach((option) => {
//          option.label = option.label.replace('(已选)', '')
          option.disabled = false
          that.routeForm.condition.forEach((item) => {
            if (option.value === item.factor) {
//              option.label = option.label + '(已选)'
              option.disabled = true
            }
          })
        })
      },
//      添加触发条件
      addCondition () {
        if (this.routeForm.condition.length > 3) {
          this.$message.error(this.$t('configLazyLoad.process.processLabel46'))
        } else {
          this.routeForm.condition.push({
            factor: '',
            contain: 'all',
            content: ''
          })
        }
      },
//      删除触发条件
      removeCondition (index) {
        this.routeForm.condition.splice(index, 1)
        this.optionsChange()
      }
    },
    beforeMount () {
      this.initData()
    },
    components: {
      questionTooltip,
      nodeSelect
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../../../assets/common.styl"
  .cust_route_node_edit
    padding 10px
    .el-table
      border none
    .el-table th.is-leaf, .el-table td
      border none
  .btn_box
    text-align right
    margin-bottom 10px
  .remark
    color #3b5998
  .node_name,.route_form_li
    width 460px
  .delete_btn
    background-color #ff6b6b
    border-color #ff6b6b
  .delete_text,.domain_btn
    color #ff6b6b !important
  .divide
    border-top 1px solid $c-border1
  .route_todo_title
    font-weight bold
    box-sizing border-box
    padding 14px 0 6px 18px
  .route_content_input
    width 200px
  .add_route_btn_box
    margin 10px 0
  .add_route_btn,.add_condition_btn
    cursor pointer
    font-size 12px
    display inline-block
    border 1px solid $c-main
    color $c-main
    width auto
    height 28px
    line-height 28px
    border-radius 4px
    text-align center
    padding 0 8px
    i
      font-size 12px
  .condition_select
    position relative
    margin-right 24px
    &:before
      content: ''
      border-top 2px solid $c-border2
      width 16px
      position absolute
      top 18px
      right -20px
  .route_form
    .remark
      padding-left 20px
  .province_select
    width 200px
  .domain_btn
    margin-left 10px
    cursor pointer
  .route_form_li
    width 500px
</style>
